package com.nbst.aop;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.nbst.annotation.OperLog;
import com.nbst.comnutil.Constants;
import com.nbst.comnutil.HttpUtil;
import com.nbst.comnutil.NormalResult;
import com.nbst.dao.mapper.mes.ExceptionLogMapper;
import com.nbst.dao.mapper.mes.SysOperationLogMapper;
import com.nbst.dao.mapper.mes.UserOperationLogMapper;
import com.nbst.model.base.ExceptionLog;
import com.nbst.model.base.SysOperationLog;
import com.nbst.model.base.User;
import com.nbst.model.base.UserOperationLog;

import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author wangwt
 * @description 切面类 操作日志记录
 * @since 2020-08-25
 **/

@Aspect
@Component
public class OperLogAspect {

    @Value("${operVer}")
    private String operVer;

    @Autowired
    private SysOperationLogMapper sysOperationLogMapper;

    @Autowired
    private UserOperationLogMapper userOperationLogMapper;

    @Autowired
    private ExceptionLogMapper exceptionLogMapper;

    private static final String BODY_LOG = "bodyLog";

    private static final String REQ_SERIVAL_NUMBER = "reqSerNum";

    /**
     * 接口调用的开始时间
     */
    private static final String START_TIME = "startTime";

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.nbst.annotation.OperLog)")
    public void operLogPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.nbst.*.controller..*.*(..)) && !execution(* com.nbst.base..controller.ExceptionController.*(..))")
    public void operExceptionLogPoinCut() {
    }


    /**
     * 在controleer方法运行前把body中得参数放入request中
     * 解决RequestBody的参数只读一次的问题
     * @param joinPoint
     */
    @Before(value = "operExceptionLogPoinCut()")
    public void beforeController(JoinPoint joinPoint){
        //获取接口的参数，设置回request
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        try {
            request.setAttribute(START_TIME, LocalDateTime.now());
            request.setAttribute(REQ_SERIVAL_NUMBER, UUID.randomUUID().toString().replace("-", "").toUpperCase());
            String bodyLog = null;
            if(joinPoint!=null && joinPoint.getArgs()!=null) {
                bodyLog = JSON.toJSONString(joinPoint.getArgs());
            }
            request.setAttribute(BODY_LOG, bodyLog);
        } catch (Exception e) {
            request.setAttribute(BODY_LOG, e.getMessage());
        }
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        SysOperationLog operlog = new SysOperationLog();
        try {
            operlog.setReqSerNum(String.valueOf(request.getAttribute(REQ_SERIVAL_NUMBER)));
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            OperLog opLog = method.getAnnotation(OperLog.class);
            if (opLog != null) {
                String operModul = opLog.operModule();
                String operType = opLog.operType();
                String operDesc = opLog.operDesc();
                // 操作模块
                operlog.setModule(operModul);
                // 操作类型
                operlog.setType(operType);
                // 操作描述
                operlog.setOperdesc(operDesc);
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求方法
            operlog.setMethod(methodName);
            // 请求的参数，获取body参数
            String reqParam = (String) request.getAttribute(BODY_LOG);
            if(reqParam!=null) {
                if (reqParam.length() > 2000) {
                    reqParam = reqParam.substring(0, 2000) + "...";
                }
                // 请求参数
                operlog.setReqParam(reqParam);
            }

            // 返回参数
            if(keys!=null) {
                String resParam = JSON.toJSONString(keys);
                if (resParam.length() > 2000) {
                    resParam = resParam.substring(0, 2000) + "...";
                }
                operlog.setResParam(resParam);
            }
            // 请求IP
            operlog.setIp(HttpUtil.getIpAddress(request));
            // 请求URI
            operlog.setUri(request.getRequestURI());
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            if(user!=null) {
                // 请求用户ID
                operlog.setUserId(user.getId());
                // 请求用户名
                operlog.setUserAccount(user.getAccount());
                // 用户姓名
                operlog.setUserName(user.getName());
            }
            // 创建时间
            operlog.setCreateTime(LocalDateTime.now());
            // 开始时间
            operlog.setStartTime((LocalDateTime) request.getAttribute(START_TIME));
            if (operlog.getStartTime()==null){
                operlog.setStartTime(LocalDateTime.now());
            }
            // 结束时间
            operlog.setEndTime(LocalDateTime.now());
            //调用时间
            operlog.setTimestamp(operlog.getEndTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() -
                    operlog.getStartTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            // 操作版本
            operlog.setVersion(operVer);
            sysOperationLogMapper.insertSelective(operlog);
            //记录用户的操作记录
            userOperLog(keys, operlog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入用户的操作记录
     * @param keys
     */
    private void userOperLog(Object keys, SysOperationLog sysOperlog){
        // 如果是NormalResult类
        if(keys instanceof NormalResult){
            NormalResult result = (NormalResult) keys;
            //查看一下有没有操作描述
            String desc = result.getDesc();
            if(!StringUtils.isEmpty(desc)){
                if(desc.length() > 1000){
                    desc = desc.substring(0,1000) + "...";
                }
                UserOperationLog userOperLog = new UserOperationLog();
                //复制相同属性的信息过来
                BeanUtils.copyProperties(sysOperlog, userOperLog);
                //这边ID不能复制
                userOperLog.setId(null);
                userOperLog.setSysLogId(sysOperlog.getId());
                //用户的操作描述
                userOperLog.setUserOperdesc(desc);
                //操作成功
                if(result.getCode().equals(Constants.OK_CODE)){
                    userOperLog.setStatus(true);
                } else {
                    userOperLog.setStatus(false);
                }
                //记录返回的信息
                String message = result.getMessage();
                if(!StringUtils.isEmpty(message)){
                    if(message.length() > 1000){
                        message = message.substring(0,1000) + "...";
                    }
                    userOperLog.setStatusMessage(message);
                }
                userOperationLogMapper.insertSelective(userOperLog);
            }
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        ExceptionLog excepLog = new ExceptionLog();
        try {
            excepLog.setReqSerNum(String.valueOf(request.getAttribute(REQ_SERIVAL_NUMBER)));
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数，获取body参数
            String reqParam = (String) request.getAttribute(BODY_LOG);
            if(reqParam!=null) {
                if (reqParam.length() > 2000) {
                    reqParam = reqParam.substring(0, 2000) + "...";
                }
                // 请求参数
                excepLog.setReqParam(reqParam);
            }

            // 请求方法名
            excepLog.setMethod(methodName);
            // 异常名称
            excepLog.setExcName(e.getClass().getName());
            // 异常信息
            String excMessage = stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace());
            if(excMessage!=null && excMessage.length() > 2000){
                excMessage = excMessage.substring(0,2000) + "...";
            }
            excepLog.setExcMessage(excMessage);
            //获取当前登录的用户
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            if(user!=null) {
                // 请求用户ID
                excepLog.setUserId(user.getId());
                // 请求用户名
                excepLog.setUserAccount(user.getAccount());
            }
            // 操作URI
            excepLog.setUri(request.getRequestURI());
            // 操作员IP
            excepLog.setIp(HttpUtil.getIpAddress(request));
            // 操作版本号
            excepLog.setVersion(operVer);
            // 发生异常时间
            excepLog.setCreateTime(LocalDateTime.now());
            exceptionLogMapper.insertSelective(excepLog);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }


    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        if(paramMap!=null) {
            for (String key : paramMap.keySet()) {
                rtnMap.put(key, paramMap.get(key)[0]);
            }
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}
